/*
 * Copyright (c) 2025 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import {GestureHandlerRootView, ScrollView} from 'react-native-gesture-handler';
import React, {useRef, useState, useCallback, useEffect} from 'react';
import {
  View,
  Text,
  TextInput,
  Button,
  Image,
  StyleSheet,
  TouchableOpacity,
  useColorScheme,
  Dimensions,
  KeyboardAvoidingView,
  Platform,
} from 'react-native';
import {AdaptiveSheet, SHEET_TYPE} from '@hadss/react-native-adaptive-sheet';
import type {AdaptiveSheetMethods} from '@hadss/react-native-adaptive-sheet';
import {BreakpointsReference, GridCol, GridRow, GridRowDirection} from '@hadss/react_native_adaptive_layout/src';
import type {ReactNode} from 'react';
import AvoidContainer from '../../components/AvoidContainer/AvoidContainer';

const Page = (): ReactNode => {
  const centerModalRef = useRef<AdaptiveSheetMethods>(null);
  const [modalIndex, setModalIndex] = useState(-1);

  // 使用 useRef 保存最新的 modalIndex 值，用于更新弹窗高度和宽度
  const modalIndexRef = useRef(modalIndex);
  const colorScheme = useColorScheme(); // 获取系统颜色方案
  const inputRef = useRef<TextInput>(null);

  // 添加状态管理弹窗高度和宽度
  const [modalHeight, setModalHeight] = useState('50%');
  const [modalWidth, setModalWidth] = useState(0);
  /**
   * Dark Mode 颜色映射
   * 根据系统颜色方案返回对应的颜色值
   */
  const colors = {
    // 背景颜色
    modalBackground: colorScheme === 'dark' ? '#1c1c1e' : '#ffffff',
    rowBackground: colorScheme === 'dark' ? '#555556' : '#f9d3d3',
    colBackground: colorScheme === 'dark' ? '#484849' : '#f4b0b0',

    // 文本颜色
    text: colorScheme === 'dark' ? '#ffffff' : '#333333',
  };

  // 根据当前屏幕方向设置初始弹窗高度和宽度
  const updateModalDimensions = useCallback(() => {
    const {width, height} = Dimensions.get('window');
    // 判断是否为横屏模式
    const isLandscape = width > height;

    setModalHeight(isLandscape ? '30%' : '50%');
    setModalWidth(isLandscape ? width * 0.9 : width * 0.7);
    if (modalIndexRef.current !== -1) {
      setModalIndex((pre) => pre + 1);
    }
  }, []);

  // 添加屏幕方向变化监听
  useEffect(() => {
    updateModalDimensions();
    const subscription = Dimensions.addEventListener('change', updateModalDimensions);

    return () => {
      subscription?.remove();
    };
  }, [updateModalDimensions]);

  // 弹窗开启/关闭状态变化回调
  const handleStateChange = useCallback(
    (index: number): void => {
      setModalIndex(index);
      if (index === -1) {
        inputRef.current?.blur(); // 手动触发失焦 隐藏键盘
      }
    },
    [modalIndex],
  );

  useEffect(() => {
    modalIndexRef.current = modalIndex;
  }, [modalIndex]);

  const list = Array.from({length: 12}, (_, i) => i);

  const handleClose = useCallback(() => {
    handleStateChange(-1);
  }, []);

  return (
    <GestureHandlerRootView style={{flex: 1}}>
      <AvoidContainer>
        <GridRow
          style={[styles.gridRow, {backgroundColor: colors.rowBackground}]}
          columns={{
            xs: 4,
            sm: 4,
            md: 8,
            lg: 12,
            xl: 12,
          }}
          gutter={40}
          breakpoints={{
            reference: BreakpointsReference.ComponentSize,
          }}
          direction={GridRowDirection.Row}>
          {list.map((item, index) => (
            <GridCol
              offset={0}
              order={0}
              span={1}
              style={[styles.gridItem, {backgroundColor: colors.colBackground}]}
              key={index}>
              <View style={styles.gridItemContent}></View>
            </GridCol>
          ))}
        </GridRow>
        <View style={styles.buttonGroup}>
          <Button title="触发自定义内容弹出窗" onPress={(): void => centerModalRef.current?.snapToIndex(0)} />
        </View>
        <AdaptiveSheet
          prefertype={SHEET_TYPE.CENTER}
          ref={centerModalRef}
          index={modalIndex} // 控制弹窗显隐及使其强制刷新
          onStateChange={handleStateChange}
          centerSheetProps={{
            width: modalWidth, // 弹窗宽度
            height: modalHeight, // 弹窗高度
            contentStyle: {
              backgroundColor: colors.modalBackground,
              borderTopLeftRadius: 20,
              borderTopRightRadius: 20,
              borderBottomLeftRadius: 20,
              borderBottomRightRadius: 20,
              padding: 0,
            },
            showHeader: false,
            backdropStyle: {
              backgroundColor: 'rgba(0, 0, 0, 0.5)',
            },
            animationConfigs: {
              duration: 250,
            },
          }}>
          <KeyboardAvoidingView
            behavior={Platform.OS === 'ios' ? 'padding' : 'height'}
            style={styles.sheetContainer}
            keyboardVerticalOffset={Platform.OS === 'ios' ? 64 : 0}>
            <View style={styles.sheetHeaderContainer}>
              <View style={styles.sheetHeader}>
                <Text style={[styles.sheetHeaderText, {color: colors.text}]}>标题</Text>
              </View>
            </View>
            <ScrollView
              showsVerticalScrollIndicator={false}
              style={styles.sheetContentContainer}
              keyboardShouldPersistTaps="handled">
              <View style={styles.sheetContent}>
                <Text style={styles.sheetContentTitle}>内容区</Text>
                <View style={styles.inputWrapper}>
                  <TextInput
                    style={styles.input}
                    ref={inputRef}
                    placeholderTextColor={colorScheme === 'dark' ? '#999' : '#666'}
                  />
                </View>
              </View>
            </ScrollView>
            <View style={styles.buttonContainer}>
              <TouchableOpacity style={styles.button} onPress={handleClose}>
                <Text style={styles.buttonText}>确认</Text>
              </TouchableOpacity>
              <TouchableOpacity style={styles.button} onPress={handleClose}>
                <Text style={styles.buttonText}>取消</Text>
              </TouchableOpacity>
            </View>
          </KeyboardAvoidingView>
        </AdaptiveSheet>
      </AvoidContainer>
    </GestureHandlerRootView>
  );
};

export default Page;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    position: 'relative',
  },
  gridRow: {
    height: '100%',
    flex: 1,
    justifyContent: 'space-around',
    backgroundColor: '#f9d3d3',
  },
  gridItem: {
    backgroundColor: '#f4b0b0',
  },
  gridItemContent: {
    height: '100%',
  },
  gridItemOdd: {
    backgroundColor: '#ae959e',
  },
  gridItemEven: {
    backgroundColor: '#fff',
  },
  buttonGroup: {
    position: 'absolute',
    width: '100%',
    height: '100%',
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sheetContainer: {
    height: '100%',
    flexDirection: 'column',
  },
  sheetHeaderContainer: {
    paddingHorizontal: 30,
  },
  sheetHeader: {
    paddingTop: 8,
    paddingBottom: 16,
    flexDirection: 'row',
    justifyContent: 'center',
    alignItems: 'center',
  },
  sheetHeaderText: {
    fontSize: 16,
    fontWeight: '500',
    color: '#333',
  },
  sheetContentContainer: {
    paddingHorizontal: 30,
    flex: 1,
    flexDirection: 'column',
  },
  sheetContent: {
    flex: 1,
    minHeight: '100%',
    backgroundColor: '#9dc3e3',
    flexDirection: 'column',
    alignItems: 'center',
  },
  sheetContentTitle: {
    fontSize: 14,
  },
  inputWrapper: {
    width: '100%',
    height: 40,
    backgroundColor: '#96bad8',
    borderRadius: 20,
    paddingHorizontal: 12,
    flexDirection: 'row',
  },
  input: {
    flex: 1,
    color: '#333',
  },
  buttonContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    paddingHorizontal: 30,
    paddingVertical: 20,
    gap: 12,
  },
  button: {
    paddingHorizontal: 16,
    backgroundColor: '#0a59f7',
    paddingVertical: 6,
    borderRadius: 20,
    alignItems: 'center',
    justifyContent: 'center',
  },
  buttonText: {
    color: '#FFFFFF',
    fontSize: 16,
    fontWeight: '500',
  },
});
